package com.isoft.airportsystem.config;

import com.isoft.airportsystem.interceptor.PermissionInterceptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.*;

import java.util.List;

@Configuration
public class WebMvcConfig implements WebMvcConfigurer {

    @Autowired
    private PermissionInterceptor permissionInterceptor;

    // 配置拦截器
    @Override
    public void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(permissionInterceptor)
                .addPathPatterns("/api/**")
                .excludePathPatterns(
                        "/api/system/login",
                        "/api/system/register",
                        "/api/system/captcha",
                        "/api/system/sendEmailCode",
                        "/api/system/sendResetCode",
                        "/api/system/resetPassword"
                );
    }

    // 配置CORS跨域
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                .allowedOrigins("http://localhost:8080", "http://localhost:8081", "http://localhost:3000", "http://localhost:5173")
                .allowedMethods("GET", "POST", "PUT", "DELETE", "OPTIONS")
                .allowedHeaders("*")
                .allowCredentials(true)
                .maxAge(3600);
    }
    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        // 确保 Jackson 转换器存在
        converters.add(new MappingJackson2HttpMessageConverter());
    }

    // 配置路由优先级 - 确保API接口优先于静态资源
    @Override
    public void configurePathMatch(PathMatchConfigurer configurer) {
        configurer.setUseSuffixPatternMatch(false)
                .setUseTrailingSlashMatch(true);
    }

    // 配置静态资源处理器
    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        // 确保API路径不被视为静态资源
        registry.addResourceHandler("/static/**")
                .addResourceLocations("classpath:/static/");

        registry.addResourceHandler("/public/**")
                .addResourceLocations("classpath:/public/");

        // 只处理非API路径的静态资源
        registry.addResourceHandler("/css/**", "/js/**", "/images/**", "/favicon.ico")
                .addResourceLocations("classpath:/static/")
                .addResourceLocations("classpath:/public/");
    }
}